<template>
  <div class="admin-question-page">
    <!-- 搜索卡片 -->
    <div class="search-card">
      <a-form
        layout="inline"
        :model="formSerchParams"
        @submit="doSerach"
        class="search-form"
      >
        <a-form-item field="appId" label="应用ID" class="form-item">
          <a-input
            allow-clear
            v-model="formSerchParams.appId"
            placeholder="请输入应用ID"
            class="search-input"
          />
        </a-form-item>

        <a-form-item field="userId" label="用户ID" class="form-item">
          <a-input
            allow-clear
            v-model="formSerchParams.userId"
            placeholder="请输入用户ID"
            class="search-input"
          />
        </a-form-item>

        <a-form-item>
          <a-button type="primary" html-type="submit" class="search-btn">
            <template #icon>
              <icon-search />
            </template>
            搜索
          </a-button>
        </a-form-item>
      </a-form>
    </div>

    <!-- 数据表格 -->
    <div class="table-card">
      <a-table
        :columns="columns"
        :data="dataList"
        :pagination="pagination"
        :row-class="setRowClass"
        @page-change="onPageChange"
        row-key="id"
      >
        <!-- 题目内容展示 -->
        <template #questionContent="{ record }">
          <a-popover position="right">
            <div class="question-preview">
              {{ getFirstQuestion(record.questionContent) }}
            </div>
            <template #content>
              <div class="question-detail">
                <div
                  v-for="(q, index) in parseQuestions(record.questionContent)"
                  :key="index"
                  class="question-item"
                >
                  <div class="question-title">{{ q.title }}</div>
                  <div
                    v-for="opt in q.options"
                    :key="opt.key"
                    class="question-option"
                  >
                    {{ opt.key }}. {{ opt.value }}
                  </div>
                </div>
              </div>
            </template>
          </a-popover>
        </template>

        <!-- 时间格式化 -->
        <template #createTime="{ record }">
          <div class="time-cell">
            {{ dayjs(record.createTime).format("YYYY-MM-DD HH:mm") }}
          </div>
        </template>

        <!-- 用户信息 -->
        <template #userInfo="{ record }">
          <div class="user-info">
            <a-avatar :size="24" :src="record.userAvatar" />
            <span class="user-id">UID: {{ record.userId }}</span>
          </div>
        </template>

        <!-- 操作列 -->
        <template #optional="{ record }">
          <a-popconfirm
            content="确认要删除该题目吗？"
            type="error"
            @ok="doDelete(record)"
          >
            <a-button status="danger">删除</a-button>
          </a-popconfirm>
        </template>
      </a-table>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, watchEffect } from "vue";
import { API } from "@/api/typings";
import message from "@arco-design/web-vue/es/message";
import { dayjs } from "@arco-design/web-vue/es/_utils/date";
import {
  deleteQuestionUsingPost,
  listQuestionByPageUsingPost,
} from "@/api/questionController";

//初始化搜索条件(不应该被修改
const initSearchParams = {
  current: 1,
  pageSize: 10,
};

//执行搜索
const doSerach = () => {
  serachParame.value = {
    ...initSearchParams,
    ...formSerchParams.value,
  };
};

const formSerchParams = ref<API.QuestionQueryRequest>({});

const serachParame = ref<API.QuestionQueryRequest>({
  ...initSearchParams,
});

const dataList = ref<API.Question[]>([]);

const total = ref<number>(0);

/**
 * 加载数据
 */
const loadData = async () => {
  const res = await listQuestionByPageUsingPost(serachParame.value);
  if (res.data.code === 0) {
    dataList.value = res.data.data?.records || [];
    total.value = res.data.data?.total || 0;
  } else {
    message.error("获取数据失败", res.data.message);
  }
};

/**
 * 当分页变化时， 触发页面的重新加载
 * @param page
 */
const onPageChange = (page: number) => {
  serachParame.value = {
    ...serachParame.value,
    current: page,
  };
};

/**
 * 删除
 * @param record
 */
const doDelete = async (record: API.Question) => {
  if (!record.id) {
    return;
  }

  const res = await deleteQuestionUsingPost({
    id: record.id,
  });
  if (res.data.code === 0) {
    loadData();
  } else {
    message.error("删除问题失败", res.data.message);
  }
};

// 监听数据变化 ，用与触发页面数据加载
watchEffect(() => {
  loadData();
});
// 解析题目内容
const parseQuestions = (content: string) => {
  try {
    return JSON.parse(content);
  } catch {
    return [];
  }
};

// 获取第一个题目
const getFirstQuestion = (content: string) => {
  const questions = parseQuestions(content);
  return questions[0]?.title || "无题目内容";
};

// 分页配置
const pagination = reactive({
  total: 0,
  current: 1,
  pageSize: 10,
  showTotal: true,
  showJumper: true,
  showPageSize: true,
  pageSizeOptions: [10, 20, 50],
});

// 表格列配置
const columns = [
  {
    title: "题目内容",
    dataIndex: "questionContent",
    slotName: "questionContent",
    width: 300,
    ellipsis: true,
  },
  {
    title: "应用ID",
    dataIndex: "appId",
    width: 100,
    align: "center",
  },
  {
    title: "创建用户",
    slotName: "userInfo",
    width: 150,
  },
  {
    title: "创建时间",
    slotName: "createTime",
    width: 150,
  },
  {
    title: "操作",
    slotName: "optional",
    width: 100,
    align: "center",
  },
];
const data = reactive([]);
</script>

<style scoped>
.admin-question-page {
  padding: 16px;
  height: 100%;
  box-sizing: border-box;
}

.search-card {
  margin-bottom: 16px;
  padding: 16px;
  background: var(--color-bg-2);
  border-radius: 4px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.search-form {
  display: flex;
  gap: 16px;
  align-items: flex-end;
}

.table-card {
  background: var(--color-bg-2);
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.question-preview {
  max-width: 280px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  cursor: pointer;
}

.question-detail {
  max-width: 400px;
  max-height: 400px;
  overflow-y: auto;
  padding: 8px;
}

.question-item {
  margin-bottom: 16px;
}

.question-title {
  font-weight: 500;
  margin-bottom: 8px;
}

.question-option {
  padding-left: 12px;
  color: var(--color-text-2);
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-id {
  font-family: monospace;
}

.time-cell {
  font-size: 12px;
  color: var(--color-text-3);
}

.stripe-row {
  background-color: var(--color-fill-1);
}
</style>
